/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Persistence;
import javax.persistence.Query;
import jpa.exceptions.NonexistentEntityException;

/**
 *
 * @author Kelompok 3
 * Kelas ini berfungsi untuk mengelola fungsi yang dibutuhkan dalam modul Comment
 * Fungsi tersebut dihungunkan dengan kelas entitas Comment yang merupakan represntasi dari tabel comments dalam database
 */

public class CommentQuery {
    /* menghubungkan dengan database sesuai dengan 
     * konfigurasi pada persistence unit
     */

    public CommentQuery() {
        emf = Persistence.createEntityManagerFactory("persistence");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    /* method untuk mengambil semua baris Comment dari tabel comments
     */
    public List<Comment> getComments(Event event) {
        List<Comment> comments = new ArrayList<Comment>();

        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("SELECT object(o) FROM Comment AS o WHERE o.idEvent=:ie ORDER BY o.idComment DESC");
            q.setParameter("ie", event);
            comments = q.getResultList();

        } finally {
            if (em != null) {
                em.close();
            }
        }
        return comments;
    }

    /* method untuk memasukkan Comment baru ke dalam tabel comments
     */
    public void createComment(Comment comment) {
        EntityManager em = getEntityManager();
        em.getTransaction().begin();
        try {
            em.persist(comment);
            em.getTransaction().commit();
        } catch (Exception e) {
            em.getTransaction().rollback();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    /* method untuk menghapus satu baris Comment pada tabel comments
     */
    public void deleteComment(int id) throws NonexistentEntityException {
        EntityManager em = getEntityManager();
        em.getTransaction().begin();
        try {
            Comment comment;
            try {
                comment = em.getReference(Comment.class, id);
                comment.getIdComment();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The comment with id " + id + " no longer exists.", enfe);
            }
            em.remove(comment);
            em.getTransaction().commit();
        } catch (Exception e) {
            em.getTransaction().rollback();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }
}
